package classcreator.DB;

import classcreator.ClassCreator;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Samus
 */
public class PText {

    private static PText instance = new PText();
    String separator = System.getProperty("line.separator");
    String folders = "C:/Netbeans Class Creator/" + ClassCreator.getInstance().getPackagename() + "/";

    public static PText getInstance() {
        return instance;
    }

    private PText() {
    }

    public void persistirMensaje(ArrayList<String> text, String nombrearchivo) {
        String filename = folders + nombrearchivo + ".java";
        File folder = new File(folders);
        if (folder.exists()) {
            try {
                Writer Candidateoutput = null;
                File Candidatefile = new File(filename);
                Candidateoutput = new BufferedWriter(new FileWriter(Candidatefile));
                for (String s : text) {
                    Candidateoutput.write(s + separator);
                }
                Candidateoutput.close();
            } catch (IOException ex) {
                Logger.getLogger(PText.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            folder.mkdirs();
            persistirMensaje(text, nombrearchivo);
        }
    }

    public ArrayList<String> leerLog(String nombrearchivo) throws IOException {
        ArrayList<String> text = new ArrayList<String>();
        try {
            FileReader fr = new FileReader(folders + nombrearchivo + ".java");
            BufferedReader entrada = new BufferedReader(fr);
            String s;
            while ((s = entrada.readLine()) != null) {
                text.add(s);
            }
        } catch (java.io.FileNotFoundException fnfex) {
            System.out.println("se presento el error: " + fnfex.toString());
        }
        return text;
    }

    public void copyLibrary() throws IOException {
        File lib = new File(System.getProperty("user.dir") + "/lib/mysql-connector-java-5.1.18-bin.jar");
        File ext = new File(folders + "connectmysqljava.jar");
        InputStream in = new FileInputStream(lib);
        OutputStream out = new FileOutputStream(ext);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
}
